package com.sxr.spring.web;

import com.sxr.integration.tenant.TenantConfigProvider;
import com.sxr.integration.util.JsonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 租户配置管理控制器
 * 提供配置刷新等管理接口
 * 
 * @author SXR
 * @since 1.0.0
 */
@ConditionalOnProperty(prefix = "sxr.file-signature", value = "enable-refresh-config", matchIfMissing = true) // 默认开启
@RestController
public class TenantConfigController {
    @Value("${sxr.file-signature.refresh-config-ip:*}")
    private String refreshConfigIp;

    private final TenantConfigProvider tenantConfigProvider;
    
    public TenantConfigController(TenantConfigProvider tenantConfigProvider) {
        this.tenantConfigProvider = tenantConfigProvider;
    }
    
    /**
     * 刷新租户配置
     * 
     * @return 刷新结果
     */
    @PostMapping("${sxr.file-signature.paths.refresh-config:#{'/refresh-config'}}/**")
    public ResponseEntity<String> refreshConfig(HttpServletRequest request) {
        try {
            if( Objects.equals(refreshConfigIp,"*") || Objects.equals(refreshConfigIp,request.getRemoteAddr())){
                boolean success = tenantConfigProvider.refresh();
                if (success) {
                    String successJson = JsonUtils.buildSuccessResponse("配置刷新成功");
                    return ResponseEntity.ok()
                            .header("Content-Type", "application/json;charset=UTF-8")
                            .body(successJson);
                }
            }
            //
            String error = "配置刷新失败";
            return failResponse(error);
        } catch (Exception e) {
            return failResponse("配置刷新异常: " + e.getMessage());
        }
    }

    private static ResponseEntity<String> failResponse(String error) {
        String errorJson = JsonUtils.buildErrorResponse(error);
        return ResponseEntity.status(500)
                .header("Content-Type", "application/json;charset=UTF-8")
                .body(errorJson);
    }
}
